package org.zero.thread;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.zero.dao.ConfigOperator;
import org.zero.entity.Request;
import org.zero.service.ServerService;
import org.zero.view.ServerWindow;

public class ServerThread implements Runnable {

	private Socket socket;
	private ServerWindow serverWindow;

	public ServerThread(Socket socket, ServerWindow serverWindow) {
		super();
		this.socket = socket;
		this.serverWindow = serverWindow;
	}

	@Override
	public void run() {
		ObjectInputStream objectInputStream = null;
		try {
			while (true) {
				objectInputStream = new ObjectInputStream(socket.getInputStream());
				Request request = (Request) objectInputStream.readObject();
				String requstServiceName = request.getRequestServiceName().toLowerCase();
				// 从文件获取 service 全限定类名
				String className = ConfigOperator.getServiceClass(requstServiceName);
				// 创建 ServerService 对象
				ServerService serverService = (ServerService) Class.forName(className).getDeclaredConstructor()
						.newInstance();
				serverService.service(request, socket, serverWindow);
			}
		} catch (IOException e) {
			serverWindow.println("[" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + "]已断开连接");
		} catch (Exception e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(serverWindow, "创建服务出错\n" + e.getMessage(),
					"错误", JOptionPane.ERROR_MESSAGE));
		}
//		finally {
//			try {
//				objectInputStream.close();
//			} catch (Exception e) {
//				SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(serverWindow,
//						"Socket 输入流关闭失败\n" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE));
//			}
//		}
	}

}
